package com.woniu.gateway.filters;

import com.woniu.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author Ma.Lei
 * @description
 * @date 2023/2/6 19:46
 */
@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录权限校验的全局过滤器
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 白名单地址放行
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (path.contains("/user/login") || path.contains("/user/register")) {// 如果是登录请求，则直接放行
            return chain.filter(exchange);
        }
        // 2. 获取token，在header中通过Authorization获取
        String token = request.getHeaders().getFirst("Authorization");
        // 如果token为空，则没有认证，直接返回
        if (StringUtils.isEmpty(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 3. 判断Redis中是否存在
        String redisToken = stringRedisTemplate.opsForValue().get("token_"+ token);
        // Redis中不存在也直接返回
        if (StringUtils.isEmpty(redisToken)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 4. 解析token，判断token是否生效
        try {
            Claims claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            // 5. token无效，则返回
            // 如果出现异常，则表示token解析错误
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 6. token续期
        stringRedisTemplate.expire("token_" + token,30*60L, TimeUnit.SECONDS);
        // 7. 放行，继续后续操作
        return chain.filter(exchange);
    }

    /**
     * 返回的值越小，执行的优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
